package org.lindom.proxy.handler;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.*;

import java.nio.charset.Charset;

import static org.lindom.proxy.handler.HexDumpProxyInboundHandler.closeOnFlush;

public class OutboundHandler extends SimpleChannelUpstreamHandler {

    private final Channel inboundChannel;

    OutboundHandler(Channel inboundChannel) {
        this.inboundChannel = inboundChannel;
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
        ChannelBuffer msg = (ChannelBuffer) e.getMessage();
//        System.out.println("<<< " + ChannelBuffers.hexDump(msg));
        System.out.print(msg.toString(Charset.defaultCharset()));
        inboundChannel.write(msg);

//        ChannelBuffer msg = (ChannelBuffer) e.getMessage();
//
//        int len = msg.readUnsignedByte();
//        int whichClient = msg.readUnsignedShort();
//        assert len == msg.readableBytes();
//        System.out.println(whichClient +" <<< " + msg.toString(Charset.defaultCharset()));
//
//        inboundChannel.write(msg);
    }

    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
        closeOnFlush(inboundChannel);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
        closeOnFlush(e.getChannel());
    }
}
